const User = require("../model/user.model");

const {
  userCreateError,
  userGetInfoError,
  userChangePasswordError,
} = require("../constant/errorType");

class UserService {
  // 获取用户信息
  async getUserInfo(query, ctx) {
    const { id, user_name, isRegister } = query;
    const whereOpt = {};
    id && Object.assign(whereOpt, { id });
    user_name && Object.assign(whereOpt, { user_name });

    try {
      const res = await User.findOne({ where: whereOpt });

      return res.dataValues;
    } catch (error) {
      if (!isRegister)
        ctx.app.emit("error", { ...userGetInfoError, message: error }, ctx);
    }
  }

  // 创建用户
  async createUser(userInfo, ctx) {
    // 插入数据
    try {
      const res = await User.create(userInfo);

      return res.dataValues;
    } catch (error) {
      ctx.app.emit("error", { ...userCreateError, message: error }, ctx);
    }
  }

  // 根据id修改数据
  async updateById(userInfo, ctx) {
    const { id, password, nickName } = userInfo;
    const whereOpt = { id };
    const newUserInfo = {};
    password && Object.assign(newUserInfo, { password });
    nickName && Object.assign(newUserInfo, { nick_name: nickName });

    try {
      const res = await User.update(newUserInfo, {
        where: whereOpt,
      });

      return res.dataValues;
    } catch (error) {
      ctx.app.emit(
        "error",
        { ...userChangePasswordError, message: error },
        ctx
      );
    }
  }
}

module.exports = new UserService();
